// interface Analyzer {
//     analyze: (xml: string) => any;
// }

import * as xml2js from 'xml2js'
import createBook, {Book} from "./createBook";

const parser = new xml2js.Parser()

export default class FeedAnalyzer {

    // private static instance: FeedAnalyzer
    bookArr: Book[] = []
    total: number = 0
    size: number = 0

    // static getInstance() {
    //     if (!FeedAnalyzer.instance) {
    //         FeedAnalyzer.instance = new FeedAnalyzer()
    //     }
    //     return FeedAnalyzer.instance
    // }

    private parseFeed(atom: any) {
        if (this.total === 0) this.total = +atom["opensearch:totalResults"][0]
        if (this.size === 0) this.size = +atom["opensearch:itemsPerPage"][0]
        const bookList = atom.entry.map((item: any) => {
            return createBook(item)
        })
        this.bookArr = this.bookArr.concat(bookList)
    }

    public async analyze(xml: string) {
        try {
            const atom = await parser.parseStringPromise(xml)
            this.parseFeed(atom.feed)
        } catch (e) {
            console.log('解析ATOM失败')
            throw e
        }
    }
}